package vn.edu.uit.chemistry;

import java.util.Map;

import vn.edu.uit.chemistry.view.ViewRowNopBaiCu;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class NopBaiCu extends Activity {

	ImageView imgView;
	Button btnBack;
	public static LinearLayout lvNopBaiCu;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.screen_nop_bai_cu);

		imgView = (ImageView) findViewById(R.id.imgView);

		btnBack = (Button) findViewById(R.id.btnBack);
		btnBack.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				imgView.removeCallbacks(onEverySecond);
				finish();
			}
		});

		lvNopBaiCu = (LinearLayout) findViewById(R.id.listNopBaiCu);
		imgView.postDelayed(onEverySecond, 0);
	}

	public Runnable onEverySecond = new Runnable() {
		public void run() {
			new UpdatePrecentAsyncTask(getApplicationContext()).execute();
		}
	};

	final class UpdatePrecentAsyncTask extends AsyncTask<Void, Void, Void> {

		private Context context;
		private ViewRowNopBaiCu viewBaiCu;
		private LayoutParams lp;
		private Map<String, ?> keys;

		public UpdatePrecentAsyncTask(Context ctx) {
			this.context = ctx;
		}

		@Override
		protected Void doInBackground(Void... param) {
			SharedPreferences prefs = context.getSharedPreferences(
					"PTNOPBAI", 0);
			keys = prefs.getAll();

			return null;
		}

		@Override
		protected void onPostExecute(final Void unused) {
			lvNopBaiCu.removeAllViews();
			for (Map.Entry<String, ?> entry : keys.entrySet()) {
				String[] values = entry.getValue().toString().split("#");
				viewBaiCu = new ViewRowNopBaiCu(context);
				viewBaiCu.setContent(values[0], Integer.parseInt(values[1]));
				lvNopBaiCu.addView(viewBaiCu.layout);
			}
			imgView.postDelayed(onEverySecond, 0);
		}

	}
}
